package com.efast.dmom.mgmt.service.les.impl;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.efast.cafe.framework.exception.ServiceException;
import com.efast.cafe.framework.jdbc.JdbcDao;
import com.efast.cafe.framework.util.SpringWebUtils;
import com.efast.dmom.mgmt.bean.les.TtWhmCountDetailBean;
import com.efast.dmom.mgmt.dao.les.TtWhmCountDetailMapper;
import com.efast.dmom.mgmt.dao.les.TtWhmCountHeaderMapper;
import com.efast.dmom.mgmt.dao.les.TwInvSkuLoctlDao;
import com.efast.dmom.mgmt.dao.master.TrBasPartSupplDao;
import com.efast.dmom.mgmt.entity.les.*;
import com.efast.dmom.mgmt.entity.master.TrBasPartSuppl;
import com.efast.dmom.mgmt.service.les.CommonService;
import com.efast.dmom.mgmt.service.les.TtWhmCountHeaderService;
import com.efast.dmom.mgmt.service.les.TwAdjDetailsService;
import com.efast.dmom.mgmt.service.les.TwAdjHeaderService;
import com.efast.dmom.mgmt.utils.Assist;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 盘点头表 服务实现类
 * </p>
 *
 * @author ChenLiPeng
 * @since 2018-06-12
 */
@Service
public class TtWhmCountHeaderServiceImpl extends ServiceImpl<TtWhmCountHeaderMapper, TtWhmCountHeader>
		implements TtWhmCountHeaderService {

	/**
	 * TT_WHM_COUNT_HEADER 盘点任务头表
	 */
	private final TtWhmCountHeaderMapper ttWhmCountHeaderMapper;
	/**
	 * TT_WHM_COUNT_DETAIL 盘点任务子表
	 */
	private final TtWhmCountDetailMapper ttWhmCountDetailMapper;
	/**
	 * 库存调整单头表 TW_ADJ_HEADER
	 */
	private final TwAdjHeaderService twAdjHeaderService;
	/**
	 * 库存调整单子表 TW_ADJ_DETAILS
	 */
	private final TwAdjDetailsService twAdjDetailsService;
	/**
	 * 库存调整单子表 TW_ADJ_DETAILS
	 */
	private final CommonService commonService;
	/**
	 * 库存表
	 */
	private final TwInvSkuLoctlDao twInvSkuLoctlDao;
	/**
	 * 零件供应商关系
	 */
	private final TrBasPartSupplDao trBasPartSupplDao;
	
	@Qualifier("jdbcDao")
	@Autowired
	private JdbcDao jdbcDao;

	@Autowired
	public TtWhmCountHeaderServiceImpl(TtWhmCountHeaderMapper ttWhmCountHeaderMapper,
			TtWhmCountDetailMapper ttWhmCountDetailMapper, TwAdjHeaderService twAdjHeaderService,
			TwAdjDetailsService twAdjDetailsService, CommonService commonService, TwInvSkuLoctlDao twInvSkuLoctlDao,
			TrBasPartSupplDao trBasPartSupplDao) {
		this.ttWhmCountHeaderMapper = ttWhmCountHeaderMapper;
		this.ttWhmCountDetailMapper = ttWhmCountDetailMapper;
		this.twAdjHeaderService = twAdjHeaderService;
		this.twAdjDetailsService = twAdjDetailsService;
		this.commonService = commonService;
		this.twInvSkuLoctlDao = twInvSkuLoctlDao;
		this.trBasPartSupplDao = trBasPartSupplDao;
	}

	@Override
	public void add(TtWhmCountHeader ttWhmCountHeader) {
		String s = jdbcDao.executeProcGetCode("tt_whm_count_header", "efast");
		// 盘点任务编号 自动生成 C+yyyymmdd+seq
		ttWhmCountHeader.setCountTaskNo(s);
		// 状态0新任务 1盘点中 2盘点完成 3关闭
		ttWhmCountHeader.setCountStatus("0");
		// 物理类型
		ttWhmCountHeader.setCountType("1");
		// 盘点级别
		ttWhmCountHeader.setCountLevel("0");
		ttWhmCountHeader.setCreateUser(SpringWebUtils.getRequestUser());
		ttWhmCountHeader.setCreateTime(new Date());
		ttWhmCountHeader.setMarkStatus(1);
		ttWhmCountHeader.setOptCounter(1);
		ttWhmCountHeaderMapper.insert(ttWhmCountHeader);
	}

	/**
	 * g)选中某行头信息，点击“生成库存调整单”，可以根据盘点的结果生成库存调整单；只有盘点完成有差异时才能生成库存调整单
	 * 
	 * @param ttWhmCountHeader
	 *            ttWhmCountHeader
	 */
	@Override
	public void generateStockBill(TtWhmCountHeader ttWhmCountHeader) {

		TtWhmCountHeader ttWhmCountHeader1 = ttWhmCountHeaderMapper.selectById(
				ttWhmCountHeader.getTtWhmCountHeaderId());

		if (!"2".equals(ttWhmCountHeader1.getCountStatus())) {
			throw new ServiceException("只有盘点完成有差异时才能生成库存调整单");
		}
		TwAdjHeader twAdjHeader = new TwAdjHeader();
		twAdjHeader.setReasonCode("盘亏");
		twAdjHeader.setReasonDesc("盘亏");
		twAdjHeader.setWarehouseNo(ttWhmCountHeader1.getWarehouseNo());
		// 调整类型0盘点调整1冲销调整
		twAdjHeader.setAdjType("0");
		// 打印状态0未打1打印完成
		twAdjHeader.setPrintStatus("0");
		String adjSheetNo = jdbcDao.executeProcGetCode("tw_adj_header", "efast");
		twAdjHeader.setAdjSheetNo(adjSheetNo);
		// 调整时间
		twAdjHeader.setAdjTime(new Date());
		// 单据状态:0新单,1发布,2完成,3关闭,4部分调整
		twAdjHeader.setSheetStatus("0");
		// 打印状态0未打1打印完成
		twAdjHeader.setPrintStatus("0");
		twAdjHeader.setMarkStatus(1);
		twAdjHeader.setCreateTime(new Date());
		twAdjHeader.setCreateUser(SpringWebUtils.getRequestUser());
		twAdjHeader.setCompanyCode(SpringWebUtils.getRequestCompany());
		twAdjHeaderService.insertNonEmptyTwAdjHeader(twAdjHeader);

		Map<String, Object> stringObjectMap = new HashMap<>(16);
		stringObjectMap.put("tt_whm_count_header_id", ttWhmCountHeader1.getTtWhmCountHeaderId());
		List<TtWhmCountDetail> ttWhmCountDetails = ttWhmCountDetailMapper.selectByMap(stringObjectMap);
		for (TtWhmCountDetail ttWhmCountDetail : ttWhmCountDetails) {
			if (ttWhmCountDetail.getCurQty().equals(ttWhmCountDetail.getActualQty1())) {
				// 没有差异不能生成库存调整单
				continue;
				// throw new ServiceException(ttWhmCountDetail.getPartNoVersion() + "没有差异不能生成库存调整单");
			}
			TwAdjDetails twAdjDetails = new TwAdjDetails();
			twAdjDetails.setTwAdjHeaderId(twAdjHeader.getTwAdjHeaderId());
			twAdjDetails.setPartNoVersion(ttWhmCountDetail.getPartNoVersion());
			twAdjDetails.setSupplNo(ttWhmCountDetail.getSupplNo());
			// 调整单行号
			twAdjDetails.setLineNo(1);
			// 订单行状态 单据状态:0新单,1发布,2完成,3关闭,4部分调整
			twAdjDetails.setLineStatus("1");
			List<TwInvSkuLoctl> twInvSkuLoctls = twInvSkuLoctlDao.selectTwInvSkuLoctl(
					new Assist(Assist.andEq("part_no_version", ttWhmCountDetail.getPartNoVersion()),
							Assist.andEq("loc_no", ttWhmCountDetail.getLocNo()),
							Assist.andEq("suppl_no", ttWhmCountDetail.getSupplNo())));
			if (twInvSkuLoctls.size() == 0) {
				throw new ServiceException(
						ttWhmCountDetail.getPartNoVersion() + "-" + ttWhmCountDetail.getLocNo() + "库存数量是0");
			}
			// 库存数量
			twAdjDetails.setQty(twInvSkuLoctls.get(0).getCurQty());
			// 可用数量
			twAdjDetails.setAvailableQty(twInvSkuLoctls.get(0).getAvailableQty());
			// 备注
			twAdjDetails.setNotes("盘点差异产生库存调整单");
			// 批次号
			twAdjDetails.setLotNo(ttWhmCountDetail.getLotNo());
			// 零件包装流水号
			twAdjDetails.setPartPackSerial(ttWhmCountDetail.getPartPackSerial());
			// 箱数
			twAdjDetails.setPackNum(ttWhmCountDetail.getPackageNum());
			// 入库包装容量
			twAdjDetails.setInboundPackQty(twInvSkuLoctls.get(0).getInboundPackQty());
			// 入库包装
			twAdjDetails.setInboundPackNo(ttWhmCountDetail.getInboundPackNo());
			List<TrBasPartSuppl> trBasPartSuppls = trBasPartSupplDao.selectTrBasPartSuppl(
					new Assist(Assist.andEq("part_no_version", ttWhmCountDetail.getPartNoVersion()),
							Assist.andEq("suppl_no", ttWhmCountDetail.getSupplNo())));
			if (trBasPartSuppls.size() == 0) {
				throw new ServiceException(ttWhmCountDetail.getPartNoVersion() + "找不到对应的零件供应商关系");
			}
			// 工厂ID
			twAdjDetails.setTmBasPlantId(trBasPartSuppls.get(0).getTmBasPlantId());
			// 工厂
			twAdjDetails.setPlantNo(trBasPartSuppls.get(0).getPlantNo());
			// 车间
			twAdjDetails.setWorkshopNo(trBasPartSuppls.get(0).getWorkshopNo());
			// 车间ID
			twAdjDetails.setTmBasWorkshopId(trBasPartSuppls.get(0).getTmBasWorkshopId());
			// 仓库
			twAdjDetails.setWarehouseNo(ttWhmCountHeader1.getWarehouseNo());
			// 库区
			TwInvSkuLoctl twInvSkuLoctl = commonService.queryWhDlocLoc(ttWhmCountDetail.getTmBasStorageId());
			twAdjDetails.setDlocNo(twInvSkuLoctl.getDlocNo());
			// 库位
			twAdjDetails.setLocNo(twInvSkuLoctl.getLocNo());
			// 调整数量
			twAdjDetails.setAdjQty(ttWhmCountDetail.getActualQty2() - ttWhmCountDetail.getCurQty());
			// 盘盈
			if (ttWhmCountDetail.getCurQty() < ttWhmCountDetail.getActualQty2()) {
				// 调整原因
				twAdjDetails.setReasonCode("盘盈");
				// 原因描述
				twAdjDetails.setReasonDesc("盘盈");
			}
			// 盘亏
			if (ttWhmCountDetail.getCurQty() > ttWhmCountDetail.getActualQty2()) {
				// 调整原因
				twAdjDetails.setReasonCode("盘亏");
				// 原因描述
				twAdjDetails.setReasonDesc("盘亏");
			}
			// 调整箱数
			twAdjDetails.setAdjPackNum(1);
			// 账目
			// twAdjDetails.setAcount();
			// sap移动类型
			// twAdjDetails.setSapTransType();
			// 成本中心
			// twAdjDetails.setCostCenter();
			// 内部订单
			// twAdjDetails.setInnerOrder();
			// 内部跟踪号
			twAdjDetails.setInbSerialNo(ttWhmCountDetail.getInbSerialNo());
			twAdjDetails.setMarkStatus(1);
			twAdjDetails.setCreateTime(new Date());
			twAdjDetails.setCreateUser(SpringWebUtils.getRequestUser());
			twAdjDetails.setCompanyCode(SpringWebUtils.getRequestCompany());
			twAdjDetailsService.insertNonEmptyTwAdjDetails(twAdjDetails);
		}

	}

	/**
	 * 确认盘点 因为我们目前做的盘点是库位的盘点，没有涉及零件包装流水号、批次号等等这种级别的，所以这些字段不用赋值，我们保留显示，后续做了别的盘点级别后再补充
	 * 盘点明细勾选复盘时，当盘点和实物一致时，还是会产生复盘任务；当实物和盘点数据不一致时，无论是否勾选复盘，都会产生复盘任务
	 * 
	 * @param ttWhmCountDetailBean
	 *            ttWhmCountDetailBean
	 */
	@Override
	public void confirm(TtWhmCountDetailBean ttWhmCountDetailBean) {
		List<TtWhmCountDetail> ttWhmCountDetailBean1 = ttWhmCountDetailBean.getTtWhmCountDetailBean();
		TtWhmCountHeader ttWhmCountHeader = new TtWhmCountHeader();
		for (TtWhmCountDetail ttWhmCountDetail : ttWhmCountDetailBean1) {
			// 当实物和盘点数据不一致时，无论是否勾选复盘，都会产生复盘任务
			if (!ttWhmCountDetail.getActualQty1().equals(ttWhmCountDetail.getCurQty())
					|| !ttWhmCountDetail.getPackageNum().equals(ttWhmCountDetail.getActualPackageNum())) {
				// 状态0新任务 1盘点中 2盘点完成 3关闭
				ttWhmCountDetail.setCountStatus("1");
				// 当不一致时候，强制复盘。
				ttWhmCountDetail.setNeedCheck(1);
				ttWhmCountDetail.setActualUser1(SpringWebUtils.getRequestUser());
				ttWhmCountDetailMapper.updateById(ttWhmCountDetail);
				ttWhmCountHeader.setCountStatus("1");
				ttWhmCountHeader.setTtWhmCountHeaderId(ttWhmCountDetail.getTtWhmCountHeaderId());
			}
			if (ttWhmCountDetail.getActualQty1().equals(ttWhmCountDetail.getCurQty())
					&& ttWhmCountDetail.getPackageNum().equals(ttWhmCountDetail.getActualPackageNum())) {
				// 状态0新任务 1盘点中 2盘点完成 3关闭
				ttWhmCountDetail.setCountStatus("2");
				ttWhmCountDetail.setActualUser1(SpringWebUtils.getRequestUser());
				ttWhmCountDetailMapper.updateById(ttWhmCountDetail);
				ttWhmCountHeader.setCountStatus("2");
				ttWhmCountHeader.setTtWhmCountHeaderId(ttWhmCountDetail.getTtWhmCountHeaderId());
			}
			ttWhmCountHeaderMapper.updateById(ttWhmCountHeader);
		}
	}

	/**
	 * 复盘 ：不能一直重复盘点
	 * 
	 * @param ttWhmCountDetailBean
	 *            ttWhmCountDetailBean
	 */
	@Override
	public void repeatConfirm(TtWhmCountDetailBean ttWhmCountDetailBean) {

		// 前置条件：满足以下条件1&（2/3）时，才可以进行复盘任务
		// 1.已经完成了初盘任务；
		// 2.明细勾选了复盘
		// 3.出现盘点差异时
		List<TtWhmCountDetail> ttWhmCountDetailBean1 = ttWhmCountDetailBean.getTtWhmCountDetailBean();
		TtWhmCountHeader ttWhmCountHeader = new TtWhmCountHeader();
		for (TtWhmCountDetail ttWhmCountDetail : ttWhmCountDetailBean1) {
			// '是否需要复盘，0不 1需要'
			boolean a = "1".equals(ttWhmCountDetail.getCountStatus()) && (1==ttWhmCountDetail.getNeedCheck()
					|| !ttWhmCountDetail.getActualQty1().equals(ttWhmCountDetail.getCurQty())
					|| !ttWhmCountDetail.getPackageNum().equals(ttWhmCountDetail.getActualPackageNum()));
			// 状态0新任务 1盘点中 2盘点完成 3关闭
			if (a) {
				// 状态0新任务 1盘点中 2盘点完成 3关闭
				ttWhmCountDetail.setCountStatus("2");
				ttWhmCountDetail.setActualUser2(SpringWebUtils.getRequestUser());
				ttWhmCountDetailMapper.updateById(ttWhmCountDetail);
				ttWhmCountHeader.setCountStatus("2");
				ttWhmCountHeader.setTtWhmCountHeaderId(ttWhmCountDetail.getTtWhmCountHeaderId());
				ttWhmCountHeaderMapper.updateById(ttWhmCountHeader);
			} else {
				System.out.println(ttWhmCountDetail.getPartNoVersion() + "不需要复盘");
			}

		}
	}
}
